const Promise = require('./promise/es6-promise.min.js')
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/**
 * 手机号的验证
 * @param {string} value 
 */
function checkPhone(value) {
  return /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(value);
}
////获取最近7天日期
//console.log(getDay(0));//当天日期
//console.log(getDay(-7));//7天前日期
//获取最近3天日期
//console.log(getDay(0));//当天日期
//console.log(getDay(-3));//3天前日期
function getDay(day){
  var today = new Date();
  var targetdayMilliseconds = today.getTime() + 1000*60*60*24*day;
  today.setTime(targetdayMilliseconds); //注意，这行是关键代码
  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  return tYear + "-" + tMonth + "-" + tDate;
}
function doHandleMonth(month){
  var m = month;
  if(month.toString().length == 1){
   m = "0" + month;
  }
  return m;
}

/**
 * 通讯地址
 */
const host = 'https://www.moreycow.com/miniapp';

//请求封装
function request(url, method, data, header = {}) {
  wx.showLoading({
    title: '加载中' //数据请求前loading
  });
  let defaultHeader = {
    'content-type': 'application/json' // 默认值
  };
  let mergeHeader = Object.assign({}, defaultHeader, header);
  return new Promise((resolve, reject) => {
    wx.request({
      url: host + url,
      method: method,
      data: data,
      header: mergeHeader,
      success: function (res) {
        if (!res || !res.data || (!res.data.success && res.data.code >= 500)) {
          console.log(res.data.exceptionClazz);
          wx.showToast({
            title: res.data.message || '服务出现问题，请重试',
            icon: 'none',
            duration: 2000
          });
        } else {
          resolve(res.data);
        }
      },
      fail: function (error) {
        console.log(error);
        wx.hideLoading();
        reject(false)
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  })
}

/**
 * 用户未登录，跳转进行登录。如果已经登录，但是token过期，自动重新登录。
 * 隐含登录进行获取appid和拼接appid
 */
function bllRequest(url, method, data, header = {}){
  let token = wx.getStorageSync('token') || '';
  if (token != ""){
    //说明已经登录过
    return new Promise(function (resolve, reject) {
      let headerData = Object.assign({}, { "Authorization": token}, header);
      request(url, method, data, headerData).then(function(response){
        if (response.code == 405) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          //自动重新登录
          loginPromise().then(function(loginRes){
            if (loginRes.code == 406 || loginRes.code == 405 || (loginRes && (loginRes.token == '' || loginRes.token == null))) {
              wx.showToast({
                title: '登录出现问题，请联系管理员',
                icon: 'none',
                duration: 2000
              });
            } else {
              let headerDatainner = Object.assign({}, { "Authorization": loginRes.token}, header);
              request(url, method, data, headerDatainner).then(function(responseinner){
                resolve(responseinner);
              }).catch(function(e){
                reject(e);
              });
            }
          }).catch(function(e){
            reject(e);
          });
        } else if (response.code == 406){ //提示用户重新登录
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          wx.showModal({
            title: '温馨提示',
            content: '您还未登录，请先登录',
            showCancel : false,
            success (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/index/index',
                });
              }
            }
          });
        } else {
          resolve(response);
        }
      }).catch(function(e){
        reject(e);
      });
    });
  } else {
    return new Promise(function (resolve, reject) {
      wx.showModal({
        title: '温馨提示',
        content: '您还未登录，请先登录',
        showCancel : false,
        success (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: '/pages/index/index',
            });
          }
        }
      });
    });
  }
}

function promiseGet(url, data, header = {}) {
  return bllRequest(url, 'GET', data, header)
}
function promisePost(url, data, header = {}) {
  return bllRequest(url, 'POST', data, header)
}

/**
 * 登录
 */
function loginPromise(){
  return new Promise(function (resolve, reject) {
    wxlogin().then(function (wxloginRes) {
      return request('/wx/user/login', 'GET', { "code": wxloginRes.code });
    }).then(function (res) {
      if (res.code == 200) {
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('userInfo', res.data);
      }
      resolve(res || {});
    }).catch(function (e) {
      reject(e);
    });
  });
}

/**
 * 调用微信登录
 */
function wxlogin() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          console.log('微信登陆成功', res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

module.exports = {
  formatTime: formatTime,
  isPhone: checkPhone,
  promiseGet: promiseGet,
  promisePost: promisePost,
  wxlogin: wxlogin,
  promiseLogin : loginPromise,
  promiseRequest : request,
  getDay : getDay
}